package com.voxel.sense.infomsg.utils.manager;

import android.text.TextUtils;
import android.util.SparseArray;

import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ListUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.ConfigEntity;
import cyy.example.com.facotry.model.api.response.ConfigEntitySpare;
import cyy.example.com.facotry.model.api.response.QueryConditionEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by chenyiyao on 2017/11/6.
 * 获取配置相关的管理器
 */

public class QueryConfigManager {
    private static boolean REQUEST_FLAG = false;//网络标记
    private static boolean REQUEST_APP_CONFIG_FLAG = false;//网络标记

    private SparseArray<SearchMenuEntity> mConditionEntities = new SparseArray();
    private static QueryConfigManager mManager;


    public static QueryConfigManager getInstance() {
        if (mManager == null) {
            synchronized (QueryConfigManager.class) {
                if (mManager == null) {
                    mManager = new QueryConfigManager();
                }
            }
        }
        return mManager;
    }

    /**
     * 刷新配置文件
     *
     * @param isForedRefresh true则从网络加载 缓存
     */
    public void loadConfig(boolean isForedRefresh) {
        getSearchMenuconfig(isForedRefresh);
    }


    public void resetDatas() {
        mConditionEntities.clear();
        SPEngine.getSPEngine().setQueryConfig("");
        //TODO:重新加载数据，配置信息
        getSearchMenuconfig(true);
        getAppConfig(true);
    }

    /**
     * 获取筛选菜单列表信息
     *
     * @param isNetLoad 传入ture 直接是从网络加载，这时只会返回null,加载成功EventBus发送消息通知
     * @return
     */
    public SparseArray<SearchMenuEntity> getSearchMenuconfig(boolean isNetLoad) {
        if (isNetLoad) {
            netSearchMenuLoad();
            return null;
        }
        //内存中没有数据
        if (mConditionEntities == null || mConditionEntities.size() < 1) {
            //首先从sp中获取，若没有则再从网络加载
            if (!TextUtils.isEmpty(SPEngine.getSPEngine().getQueryConfig())) {
                Gson gson = new Gson();
                SPEngine.getSPEngine().getQueryConfig();
                //定义需要转换的类型
                Type type = new TypeToken<List<SearchMenuEntity>>() {
                }.getType();
                //从sp中获取字符串进行转换
                List<SearchMenuEntity> bean = gson.fromJson(SPEngine.getSPEngine().
                        getQueryConfig(), type);
                if (bean != null && bean.size() > 0) {
                    mConditionEntities = filterMenuData(bean);
                } else {
                    netSearchMenuLoad();
                }
            } else if (!REQUEST_FLAG) {
                netSearchMenuLoad();
            }
        }
        return mConditionEntities;
    }


    /**
     * 网络加载筛选配置信息
     */
    private void netSearchMenuLoad() {
        REQUEST_FLAG = true;
        NetHelper.getSearchMenuConfig(new DataSource.Callback<BaseEntity<List<SearchMenuEntity>>>() {
            @Override
            public void onDataNotAvailable(String strRes, int reqId) {
                REQUEST_FLAG = false;
                EventEntity eventEntity = new EventEntity(EventBusConstants.QUERY_CONFIG,
                        EventBusConstants.FAILURE);
            }

            @Override
            public void onDataLoaded(BaseEntity<List<SearchMenuEntity>> data, int reqId) {
                REQUEST_FLAG = false;
                if (data != null && data.isSuccess()) {
                    List<SearchMenuEntity> dataList = data.getData();
                    mConditionEntities = filterMenuData(dataList);
                    //将数据缓存到sp中
                    Gson gson = new Gson();
                    SPEngine.getSPEngine().setQueryConfig(gson.toJson(dataList));
                    //加载成功，发送通知
                    SendMsg();
                }
            }
        });
    }

    /**
     * id  1行业类型  2监管性质 3监管等级 13发布类型  16企业排序类型 17用户角色 19部门类型 20中队类型
     * 27组织类型 28任务类型  30任务登记
     *
     * @param bean
     * @return
     */
    private SparseArray<SearchMenuEntity> filterMenuData(List<SearchMenuEntity> bean) {
        //TODO: 转换可能存问题，还需检查
        SparseArray<SearchMenuEntity> arrays = new SparseArray();
        for (Object entity : bean) {
            if (entity instanceof SearchMenuEntity) {
                SearchMenuEntity data = (SearchMenuEntity) entity;
                if ("1".equals(data.getId()) ||
                        "2".equals(data.getId()) ||
                        "3".equals(data.getId()) ||
                        "13".equals(data.getId()) ||
                        "16".equals(data.getId()) ||
                        "17".equals(data.getId()) ||
                        "19".equals(data.getId()) ||
                        "27".equals(data.getId()) ||
                        "28".equals(data.getId()) ||
                        "20".equals(data.getId()) ||
                        "30".equals(data.getId())) {
                    try {
                        arrays.append(Integer.parseInt(data.getId()), data);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return arrays;
    }


    private void SendMsg() {
        L.d("列表拉去成功，发送消息");
        EventBus.getDefault().post(
                new EventEntity(String.valueOf(
                        EventBusConstants.QUERY_CONFIG),
                        EventBusConstants.SUCCEED));
    }


    //网络取获取app的数据
    public void getAppConfig(boolean isNetLoad) {
        if (REQUEST_APP_CONFIG_FLAG) {
            return;
        }
        REQUEST_APP_CONFIG_FLAG = true;

        NetHelper.getAPPConfig(new DataSource.Callback<BaseEntity<ConfigEntitySpare>>() {
            @Override
            public void onDataNotAvailable(String strRes, int reqId) {
                REQUEST_APP_CONFIG_FLAG = false;//网咯回调改变标记
            }

            @Override
            public void onDataLoaded(BaseEntity<ConfigEntitySpare> body, int reqId) {
                REQUEST_APP_CONFIG_FLAG = false;//网咯回调改变标记
                if (body.isSuccess()) {
                    ConfigEntitySpare entity = body.getData();
                    //个人位置刷新时间
                    String personalRefreshTime = entity.getPersonalRefreshTime();
                    if (!TextUtils.isEmpty(personalRefreshTime)) {
                        try {
                            Long v = Long.parseLong(personalRefreshTime);
                            SPEngine.getSPEngine().setMyLocationRefreshTime(v);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    //上传视频最大限制
                    String videoUploadSizeLimit = entity.getVideoUploadSizeLimit();
                    if (!TextUtils.isEmpty(videoUploadSizeLimit)) {
                        try {
                            Long v = Long.parseLong(videoUploadSizeLimit);
                            SPEngine.getSPEngine().setVideoUploadMaxSize(v);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    //表格实时数据刷新时间
                    String realTimeDataRefreshTime = entity.getRealTimeDataRefreshTime();
                    if (!TextUtils.isEmpty(realTimeDataRefreshTime)) {
                        try {
                            Long v = Long.parseLong(realTimeDataRefreshTime);
                            SPEngine.getSPEngine().setRealDataRefreshTime(v);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    //地图人员刷新时间
                    String personRefreshTime = entity.getPersonRefreshTime();
                    if (!TextUtils.isEmpty(personRefreshTime)) {
                        try {
                            Long v = Long.parseLong(personRefreshTime);
                            SPEngine.getSPEngine().setMapPersonLocationRefreshTime(v);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    EventBus.getDefault().post(new EventEntity(EventBusConstants.APP_CONFIG_LOAD_SUCCEED, body));
                }
            }
        });
    }

    /**
     * 获取角色类型
     */
    public List<ConfigEntity.BodyBean.PersonRolesBean> getPersonRoles() {
        List<ConfigEntity.BodyBean.PersonRolesBean> list = null;
        //从sp中获取json实体
        String personRolesList = SPEngine.getSPEngine().getAppConfigJso();
        if (!TextUtils.isEmpty(personRolesList)) {
            Gson gson = new Gson();
            ConfigEntity.BodyBean bean = gson.fromJson(personRolesList, ConfigEntity.BodyBean.class);
            List<ConfigEntity.BodyBean.PersonRolesBean> personRoles = bean.getPersonRoles();
            //拿到集合进行判断
            if (personRoles != null && personRoles.size() > 0) {
                list = personRoles;
            } else {
//                getAppConfig();
            }
        } else {
//            getAppConfig();
        }
        return list;
    }

    /**
     * 获取任务类型集合 usage
     *
     * @return 角色类型的集合，返回null 的时候，则数据还没有加载到
     */
    public SearchMenuEntity getTaskType() {
        return getMenuData(28);
    }

    /**
     * 获取任务等级
     *
     * @return
     */
    public SearchMenuEntity getTaskLevel() {
        return getMenuData(30);
    }

    public SearchMenuEntity getMenuData(int key) {
        SearchMenuEntity data = null;
        //首先从内存中取
        if (mConditionEntities != null && mConditionEntities.size() > 0) {
            data = mConditionEntities.get(key);
        } else {
            //内存没有则调用加载方法
            SparseArray<SearchMenuEntity> searchMenuconfig = getSearchMenuconfig(false);
            if (searchMenuconfig != null && searchMenuconfig.size() > 0) {
                data = searchMenuconfig.get(key);
            }
        }
        return data;
    }

    /**
     * 获取违法记录筛选筛选的条件
     *
     * @return list
     */
    public List<QueryConditionEntity.BodyBean.IllegalRecordBean> getSmartConfig() {
        //TODO:暂无该数据，需完善
        List<QueryConditionEntity.BodyBean.IllegalRecordBean> list = new ArrayList<>();
//        QueryConditionEntity getconfig = getSearchMenuconfig(false);
//        if (getconfig != null) {
//            list = getconfig.getBody().getIllegalRecord();
//        }

        return list;
    }
//

    /**
     * 获取行业类型信息
     *
     * @return
     */
    public SearchMenuEntity getIndustryType() {
        return getMenuData(1);
    }

    /**
     * 获取监管性质数据
     *
     * @return
     */
    public SearchMenuEntity getSuperviseNatureIdData() {
        return getMenuData(2);
    }


    /**
     * 获取监管等级数据
     *
     * @return
     */
    public SearchMenuEntity getSuperviseGradeIdData() {
        return getMenuData(3);
    }

    /**
     * 获取发布类型
     *
     * @return
     */
    public SearchMenuEntity getPublishFileType() {
        return getMenuData(13);
    }

    /**
     * 获取公司智能排序类型
     *
     * @return
     */
    public SearchMenuEntity getFirmSortType() {
        return getMenuData(16);
    }

    /**
     * 获取公司智能排序类型
     * squadron
     *
     * @return
     */
    public SearchMenuEntity getSquadronType() {
        return getMenuData(20);
    }

    /**
     * 获取公司部门类型
     *
     * @return
     */
    public SearchMenuEntity getDepartmentType() {
        return getMenuData(19);
    }

    /**
     * 根据code获取指定的部门类型数据
     *
     * @param code
     * @return
     */
    public SearchMenuEntity.StaticSystemConstantDetailsBean getSpecialDeparmentType(String code) {
        SearchMenuEntity entity = getDepartmentType();
        if (entity != null && entity.getStaticSystemConstantDetails() != null) {
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : entity.getStaticSystemConstantDetails()) {
                if (bean.getConstantCode().equals(code)) {
                    return bean;
                }
            }
        }
        return null;
    }

    /**
     * 获取用户角色类型
     *
     * @return
     */
    public SearchMenuEntity getRoleType() {
        return getMenuData(17);
    }

    /**
     * 获取用户角色类型
     *
     * @return
     */
    public SearchMenuEntity getOrganizationType() {
        return getMenuData(27);
    }


    public String getTaskRoleOrganizationId() {
        String id = "";
        SearchMenuEntity organizationType = getOrganizationType();
        if (organizationType != null && !ListUtil.isEmpty(organizationType.getStaticSystemConstantDetails())) {
            List<SearchMenuEntity.StaticSystemConstantDetailsBean> staticSystemConstantDetails = organizationType.getStaticSystemConstantDetails();
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : staticSystemConstantDetails) {
                if ("角色类型".equals(bean.getConstantName())) {
                    id = bean.getConstantCode();
                    break;
                }
            }
        }
        return id;
    }

}
